#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
云盘分享工具模块

提供天翼云盘分享数据抓取和解析功能
"""

import sys
import os
import requests
import json
from typing import Dict, Any, Optional, List
from urllib.parse import urlparse, parse_qs
import time
import re

# 添加项目根目录到路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))

from src.common.unified_logging import get_logger
from src.common.utils.file_utils import format_file_size
from src.common.utils.tianyi_utils import (
    validate_tianyi_share_code, parse_tianyi_share_url
)

logger = get_logger(__name__)


def get_tianyi_share_data(share_code: str, access_code: str = "", depth: int = 3) -> Dict[str, Any]:
    """
    获取天翼云盘分享数据
    
    Args:
        share_code: 分享码
        access_code: 访问码
        depth: 抓取深度
        
    Returns:
        包含分享数据的字典
    """
    try:
        # 构建分享链接
        share_url = f"https://cloud.189.cn/t/{share_code}"
        
        # 模拟请求头
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
            'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
            'Accept-Encoding': 'gzip, deflate, br',
            'Connection': 'keep-alive',
            'Upgrade-Insecure-Requests': '1',
        }
        
        session = requests.Session()
        session.headers.update(headers)
        
        # 第一步：访问分享页面
        response = session.get(share_url, timeout=30)
        response.raise_for_status()
        
        # 解析页面获取分享信息
        share_info = _parse_share_page(response.text, share_code)
        
        if not share_info.get('success'):
            return {
                'success': False,
                'error': share_info.get('error', '解析分享页面失败'),
                'shareInfo': {}
            }
        
        # 如果需要访问码
        if share_info.get('needAccessCode') and access_code:
            # 提交访问码
            verify_result = _verify_access_code(session, share_code, access_code)
            if not verify_result.get('success'):
                return {
                    'success': False,
                    'error': verify_result.get('error', '访问码验证失败'),
                    'shareInfo': share_info
                }
        
        # 获取文件列表
        file_list = _get_file_list(session, share_code, depth)
        
        return {
            'success': True,
            'shareInfo': share_info,
            'fileList': file_list,
            'crawlTime': time.time()
        }
        
    except requests.RequestException as e:
        logger.error(f"网络请求失败: {e}")
        return {
            'success': False,
            'error': f'网络请求失败: {str(e)}',
            'shareInfo': {}
        }
    except Exception as e:
        logger.error(f"获取天翼云盘分享数据失败: {e}")
        return {
            'success': False,
            'error': f'获取分享数据失败: {str(e)}',
            'shareInfo': {}
        }


def _parse_share_page(html_content: str, share_code: str) -> Dict[str, Any]:
    """解析分享页面"""
    try:
        # 提取分享信息
        share_info = {
            'shareCode': share_code,
            'shareName': '',
            'shareUser': '',
            'shareTime': '',
            'needAccessCode': False,
            'success': True
        }
        
        # 使用正则表达式提取分享名称
        name_match = re.search(r'<title[^>]*>([^<]+)</title>', html_content)
        if name_match:
            title = name_match.group(1).strip()
            # 移除"天翼云盘"等后缀
            share_info['shareName'] = re.sub(r'\s*-\s*天翼云盘.*$', '', title)
        
        # 检查是否需要访问码
        if '请输入访问码' in html_content or 'access_code' in html_content:
            share_info['needAccessCode'] = True
        
        # 提取分享用户信息
        user_match = re.search(r'分享者[：:]\s*([^<\n]+)', html_content)
        if user_match:
            share_info['shareUser'] = user_match.group(1).strip()
        
        return share_info
        
    except Exception as e:
        logger.error(f"解析分享页面失败: {e}")
        return {
            'success': False,
            'error': f'解析分享页面失败: {str(e)}'
        }


def _verify_access_code(session: requests.Session, share_code: str, access_code: str) -> Dict[str, Any]:
    """验证访问码"""
    try:
        # 这里应该实现具体的访问码验证逻辑
        # 由于天翼云盘的API可能会变化，这里提供一个基础框架
        
        verify_url = f"https://cloud.189.cn/api/open/share/checkAccessCode.action"
        data = {
            'shareCode': share_code,
            'accessCode': access_code
        }
        
        response = session.post(verify_url, data=data, timeout=30)
        result = response.json()
        
        if result.get('res_code') == 0:
            return {'success': True}
        else:
            return {
                'success': False,
                'error': result.get('res_message', '访问码验证失败')
            }
            
    except Exception as e:
        logger.error(f"验证访问码失败: {e}")
        return {
            'success': False,
            'error': f'验证访问码失败: {str(e)}'
        }


def _get_file_list(session: requests.Session, share_code: str, depth: int) -> List[Dict[str, Any]]:
    """获取文件列表"""
    try:
        # 这里应该实现具体的文件列表获取逻辑
        # 由于天翼云盘的API可能会变化，这里提供一个基础框架
        
        file_list = []
        
        # 模拟文件列表结构
        # 实际实现需要调用天翼云盘的API
        
        return file_list
        
    except Exception as e:
        logger.error(f"获取文件列表失败: {e}")
        return []


def extract_share_data(raw_data: Dict[str, Any]) -> Dict[str, Any]:
    """
    提取和标准化分享数据
    
    Args:
        raw_data: 原始分享数据
        
    Returns:
        标准化后的分享数据
    """
    try:
        if not raw_data.get('success'):
            return raw_data
        
        share_info = raw_data.get('shareInfo', {})
        file_list = raw_data.get('fileList', [])
        
        # 统计信息
        total_files = len([f for f in file_list if f.get('type') == 'file'])
        total_folders = len([f for f in file_list if f.get('type') == 'folder'])
        total_size = sum(f.get('size', 0) for f in file_list if f.get('type') == 'file')
        
        extracted_data = {
            'success': True,
            'shareCode': share_info.get('shareCode', ''),
            'shareName': share_info.get('shareName', ''),
            'shareUser': share_info.get('shareUser', ''),
            'shareTime': share_info.get('shareTime', ''),
            'statistics': {
                'totalFiles': total_files,
                'totalFolders': total_folders,
                'totalSize': total_size
            },
            'fileList': file_list,
            'crawlTime': raw_data.get('crawlTime', time.time())
        }
        
        return extracted_data
        
    except Exception as e:
        logger.error(f"提取分享数据失败: {e}")
        return {
            'success': False,
            'error': f'提取分享数据失败: {str(e)}'
        }


# format_file_size 和 validate_share_code 函数已移动到 src.common.utils.tianyi_utils